/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ucab.desarrollo.viajesbook.api;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 *
 * @author Magaly Romero
 */

public class ServiceXML {

    public InputStream getXml(String URL) throws Exception {
        return (get(URL));
    }

    public String convertStreamToString(InputStream is)
            throws IOException {
        /*
         * To convert the InputStream to String we use the
         * Reader.read(char[] buffer) method. We iterate until the
         * Reader return -1 which means there's no more data to
         * read. We use the StringWriter class to produce the string.
         */
        if (is != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(
                        new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        } else {
            return "";
        }
    }

    public static InputStream get(String urlStr) throws Exception {
        return readFrom(urlStr, null);
    }

    public static InputStream post(String urlStr, String post) throws Exception {
        return readFrom(urlStr, post);
    }

    private static InputStream readFrom(String urlStr, String postStr)
        throws MalformedURLException, IOException {

        URLConnection conn = new URL(urlStr).openConnection();
        conn.setDoInput(true);
        if (postStr != null && postStr.length() > 0) {
            conn.setDoOutput(true);
            DataOutputStream output =
                    new DataOutputStream(conn.getOutputStream());
            output.writeBytes(postStr);
            output.flush();
            output.close();
        }
        return conn.getInputStream();
    }

}
